package com.enjoy.concurrent.ch2;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁测试
 */
@Slf4j(topic = "enjoy")
public class ReadWriteLockTest {

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private final Lock readLock = readWriteLock.readLock();

    private final Lock writeLock = readWriteLock.writeLock();

    private int i;

    public void read() {
        try {
            readLock.lock();
            log.info(i + "");
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        } finally {
            readLock.unlock();
        }
    }

    public void write() {
        try {
            writeLock.lock();
            i = i + 1;
            log.info(i + "");
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        } finally {
            writeLock.unlock();
        }
    }

    @Test
    public void test1() throws InterruptedException {
        //读读并发
        new Thread(this::read, "t1").start();
        new Thread(this::read, "t2").start();
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Test
    public void test2() throws InterruptedException {
        //读写互斥
        new Thread(this::read, "t1").start();
        new Thread(this::write, "t2").start();
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Test
    public void test3() throws InterruptedException {
        //写读互斥
        new Thread(this::write, "t1").start();
        new Thread(this::read, "t2").start();
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Test
    public void test4() throws InterruptedException {
        //写写互斥
        new Thread(this::write, "t1").start();
        new Thread(this::write, "t2").start();
        Thread.sleep(Integer.MAX_VALUE);
    }
}
